<template>
  <el-dialog
    :visible.sync="visible"
    title="权限配置"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-tree
      ref="tree"
      :data="typeTree"
      show-checkbox
      node-key="key"
      :props="treeProps"
    >
    </el-tree>
    <div slot="footer">
      <el-button size="mini" @click="cancel">取消</el-button>
      <el-button size="mini" type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
const URL_GET_USER_SUBSCRIBE = '/sys/roleSubscribeRel/selIndustryById'
const URL_USER_SET_SUBSCRIBE = '/sys/roleSubscribeRel/setUserSubscribe'

const URL_GET_ALL_TYPE = '/cgjybzIndustry/selAllType'

export default {
  name: 'SubscribeModal',
  data () {
    return {
      userId: null,
      visible: false,
      typeTree: [],
      selectedKeys: [],
      treeProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    init (userId) {
      this.userId = userId
      this.visible = true
      this.initData()
    },
    cancel () {
      this.visible = false
    },
    confirm () {
      const keys = this.$refs.tree.getCheckedKeys().filter(k => k != null)
      this.$http.post(URL_USER_SET_SUBSCRIBE + '?id=' + this.userId, keys).then(_ => {
        this.$message.success('修改成功')
        this.cancel()
      })
    },
    initData () {
      this.$http.get(URL_GET_ALL_TYPE).then(({ data: resp }) => {
        const originData = resp.data
        const m = originData.reduce((t, c) => {
          const { division } = c
          if (!t[division]) {
            t[division] = []
          }
          t[division].push(c)
          return t
        }, {})

        this.typeTree = Object.keys(m).map((d) => {
          return {
            name: d,
            children: m[d]
          }
        })
      })

      this.$http.get(URL_GET_USER_SUBSCRIBE + '?id=' + this.userId).then(({ data: resp }) => {
        console.log(resp)
        const keys = resp.data.map(r => r.key)
        this.$refs.tree.setCheckedKeys(keys)
      })
    }
  }
}
</script>

<style></style>
